package com.rtmart.pdaservice;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.ExtendedListener;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

import java.net.URISyntaxException;

public class PDAService extends Service {

    public static final String TAG = "PDAServer";
    public static final String TOPIC = "topic/3023";

    WifiConnector wac;
    WifiManager wifiManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "OnCreate 服务启动时调用");
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wac = new WifiConnector(wifiManager);
        try {
            testMqtt();
        } catch (URISyntaxException e) {
            Log.e(TAG, "testMqtt failed", e);
        }
    }

    //服务被关闭时调用
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy 服务关闭时");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        return super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    private void testMqtt() throws URISyntaxException {
        MQTT mqtt = new MQTT();
        mqtt.setHost("10.97.104.189", 61613);
        mqtt.setVersion("3.1.1");
        mqtt.setUserName("admin");
        mqtt.setPassword("password");
//        mqtt.setClientId(intToIp(wifiManager.getConnectionInfo().getIpAddress()));
//        mqtt.setCleanSession(false);

        final CallbackConnection connection = mqtt.callbackConnection();

        //设置监听
        connection.listener(new ExtendedListener() {
            @Override
            public void onPublish(UTF8Buffer topic, Buffer body, Callback<Callback<Void>> ack) {
                Log.d(TAG, "onPublish " + topic.toString() + " " + body.toString());
                String[] msg = body.toString().split(":");
                if (msg.length == 3 && msg[1].trim().equals("TXD")){
                    try {
                        wac.connect("TXD", msg[2].trim());
                    } catch (Exception e) {
                        Log.d(TAG, "change wifi password exception");
                    }
                }
//                NotificationManager notifyManager
//                        = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//                NotificationCompat.Builder builder = new NotificationCompat
//                        .Builder(MainActivity.this)
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentTitle(topic.toString())
//                        .setContentText(body.ascii().toString());
//                notifyManager.notify(1, builder.build());
            }

            @Override
            public void onConnected() {
                Log.d(TAG, "onConnected");
            }

            @Override
            public void onDisconnected() {

                Log.d(TAG, "onDisconnected");
            }

            @Override
            public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
                Log.d(TAG, "onPublish " + topic.toString() + " " + body);
                ack.run();
            }

            @Override
            public void onFailure(Throwable value) {
                Log.d(TAG, "onFailure");
            }
        });

        //连接服务器
        connection.connect(new Callback<Void>() {
            public void onFailure(Throwable value) {
                Log.d(TAG, "connect failure");
            }

            public void onSuccess(Void v) {
                //订阅消息
                Topic[] topics = {new Topic(TOPIC, QoS.AT_LEAST_ONCE)};
                connection.subscribe(topics, new Callback<byte[]>() {
                    public void onSuccess(byte[] qoses) {
                        Log.d(TAG, "subscribe success");
                    }

                    public void onFailure(Throwable value) {
                        Log.e(TAG, "subscribe failure", value);
                        connection.disconnect(null); //断开连接
                    }
                });

                //发布一个消息
//                byte[] payload = "hello world".getBytes();
//                connection.publish(TOPIC, payload, QoS.AT_LEAST_ONCE, false, new Callback<Void>() {
//                    public void onSuccess(Void v) {
//                        Log.d(TAG, "publish success");
//                    }
//
//                    public void onFailure(Throwable value) {
//                        Log.e(TAG, "publish failure", value);
////                        connection.disconnect(null); //断开连接
//                    }
//                });

//                //断开连接
//                connection.disconnect(new Callback<Void>() {
//                    public void onSuccess(Void v) {
//                        Log.d(TAG, "disconnect success");
//                    }
//
//                    public void onFailure(Throwable value) {
//                        Log.d(TAG, "disconnect failure");
//                        // disconnects是不会失败的,也就是这里永远不会被调到
//                    }
//                });
            }
        });
    }
    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }
}
